import React, { useEffect, useRef, useState } from 'react'
import initNodes from '@/mock/initNodes'
import WorkFlow from '@/components/WorkFlow'
import { Tags, Card } from '@/components'
import { Space, Button, Tag, Drawer, Row, message } from 'antd'
import { PlayBookService } from '@/service'
import styles from './index.module.less'

const PlaybookDetail = props => {
  const { detail, setDetail, onOpen, setIsRefresh } = props
  const { type, visible, data } = detail

  const graphRef = useRef()

  const handlePlaySave = () => {
    const { id, ...wf_data } = data

    graphRef.current.getGraphData().then(graphData => {
      wf_data.graphData = graphData
      const service =
        type === 'update'
          ? PlayBookService.updatePlay({
              id,
              wf_data: wf_data,
              is_publish: true
            })
          : PlayBookService.createPlay({
              wf_data: wf_data,
              is_publish: true
            })

      service
        .then(res => {
          setDetail(detail => ({ ...detail, visible: false }))
          message.success(`${type === 'add' ? '创建' : '修改'}剧本成功！`)
          setIsRefresh(true)
        })
        .catch(err => {
          message.error(err)
        })
    })
  }

  return (
    <Drawer
      className={styles['playbook-detail-drawer']}
      visible={visible}
      width="100%"
      closable={false}
      bodyStyle={{ padding: 0, display: 'flex', flexDirection: 'column' }}
      destroyOnClose
    >
      <Card
        bordered={false}
        extra={
          <Space>
            <Button
              onClick={() => {
                setDetail({ visible: false, data: {} })
              }}
            >
              返回
            </Button>
            {type !== 'check' && (
              <Button type="primary" onClick={handlePlaySave}>
                保存
              </Button>
            )}
          </Space>
        }
      >
        <Row justify="space-between">
          <Space direction="vertical">
            <Space>
              {data.type && <Tag className="type-tag">{data.type}</Tag>}
              <span>{data.name}</span>
              {/* <span>{data.version}</span> */}
              {data?.tags?.map?.(tag => (
                <Tag className='tag-item' key={tag}>{tag}</Tag>
              ))}
              {/* <Tags tags={data.tags} disabled /~ onTagsChange={onTagsChange} ~/ />*/}
            </Space>
            {data.description && (
              <Space>
                <span>剧本描述：</span>
                <span>{data.description}</span>
              </Space>
            )}
          </Space>
          {type !== 'check' && (
            <Button type="primary" onClick={() => onOpen('edit')}>
              修改剧本信息
            </Button>
          )}
        </Row>
      </Card>
      <WorkFlow
        ref={graphRef}
        data={data.graphData ?? initNodes}
        meta={{ name: data.name, mode: type }}
      />
    </Drawer>
  )
}
export default PlaybookDetail
